package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/6/8 21:11
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    /**
     * @return 跳转到fileupload.jsp页面
     */
    @RequestMapping("/toload")
    public String toUpload(){
        return "fileupload";
    }

    /**
     * 文件上传 MultipartFile接口用来接收上传的文件
     * @param source 变量名必须等于页面上传域的name属性
     * @param request request域
     * @return 返回文件路径
     * @throws IOException 异常
     */
    @RequestMapping("/test1")
    @ResponseBody
    public String test1(MultipartFile source, HttpServletRequest request) throws IOException {
        //1.获取完整文件名
        String filename = source.getOriginalFilename();
        //获取文件大小
        long size = source.getSize();
        //获取文件内容
        InputStream inputStream = source.getInputStream();
        //2.获取文件保存路径
        String realPath = request.getServletContext().getRealPath("/upload");
        //判断路径是否存在,不存在就创建
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        //3.持久化保存到硬盘上
        source.transferTo(new File(realPath+"\\"+filename));
        //4.返回文件保存的路径字符串
        return "http://localhost:8080/upload/"+filename;
    }
}
